package edu.fdzc.shop.service;

import edu.fdzc.shop.dao.ProductMapper;
import edu.fdzc.shop.dto.CategoryDto;
import edu.fdzc.shop.dto.ProductDto;
import edu.fdzc.shop.dto.ReviewDto;
import edu.fdzc.shop.entity.Product;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * DESCRIPTION:
 * 商品service
 */
@Service
public class ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private ReviewService reviewService;

    /**
     * 新增商品
     * @param productDto
     * @return
     */
    public Boolean add(ProductDto productDto) {
        Product product = new Product();
        BeanUtils.copyProperties(productDto, product);
        product.setId(UUID.randomUUID().toString());
        return productMapper.insert(product) > 0;
    }

    /**
     * 搜索商品
     * @param productDto
     * @return
     */
    public List<ProductDto> search(ProductDto productDto) {
        Product product = new Product();
        BeanUtils.copyProperties(productDto, product);
        List<Product> productList = productMapper.filter(product);
        return productList.stream()
                .map(ProductService::convertDto)
                .collect(Collectors.toList());
    }

    /**
     * 查看指定商品
     * @param productId
     * @return
     */
    public ProductDto getProductById(String productId) {
        Product product = productMapper.findById(productId);
        ProductDto productDto = new ProductDto();
        BeanUtils.copyProperties(product, productDto);
        // 获取指定商品分类信息
        CategoryDto categoryDto = categoryService.getCategoryById(product.getCategoryId());
        productDto.setCategoryName(categoryDto.getCategoryName());
        //查看评论列表
        List<ReviewDto> reviewDtoList = reviewService.list(productDto.getId());
        productDto.setReviewDtoList(reviewDtoList);
        return productDto;
    }

    /**
     * 修改商品
     * @param productDto
     * @return
     */
    public Boolean update(ProductDto productDto) {
        Product product = new Product();
        BeanUtils.copyProperties(productDto, product);
        product.setUpdateTime(new Date());
        return productMapper.update(product) > 0;
    }

    /**
     * 删除商品
     * @param productId
     * @return
     */
    public Boolean delete(String productId) {
        return productMapper.delete(productId) > 0;
    }

    public static ProductDto convertDto(Product product) {
        if(product != null){
            ProductDto productDto = new ProductDto();
            BeanUtils.copyProperties(product, productDto);
            return productDto;
        }
        return null;
    }
}
